<template>
<form @submit="loginFun" v-if="setting">
	<image mode='widthFix' class='wx_login_bg' src='https://image1.sansancloud.com/xianhua/2019_11/26/9/32/2_137.jpg?x-oss-process=style/preview_120'></image>
	<view class='wz_login_container'>
	  <view class='wx_logo_block'>
	    <image mode='aspectFit' class='wx_logo_img' :src='setting.platformSetting.logo&&setting.platformSetting.logo!="undefined"?setting.platformSetting.logo:"https://image1.sansancloud.com/sansancloud/2018_7/14/11/21/37_175.jpg?x-oss-process=style/preview_120"'></image>
	  </view>
	  <view class='wx_botton_block'>
	     <!-- <button v-if="!authorizationState" class='wx_botton_item login' :loading="loginState" open-type='getUserInfo' @getuserinfo="bindGetUserInfo" :style="{background:setting.platformSetting?setting.platformSetting.defaultColor:'#2269d5',border:'1rpx solid'+(setting.platformSetting?setting.platformSetting.defaultColor:'#2269d5')}">
             微信授权登录
         </button> -->
         <button class='wx_botton_item login' :loading="loginState" open-type='getPhoneNumber' @getphonenumber="getPhoneNumber" :style="{background:setting.platformSetting?setting.platformSetting.defaultColor:'#2269d5',border:'1rpx solid'+(setting.platformSetting?setting.platformSetting.defaultColor:'#2269d5')}">
             本机号码一键登录
         </button>
	     <view class='forget_password' @tap.stop="toAppLoginFun">
	       <text>更换手机号</text>
	       <image class='forget_password_icon' src='https://image1.sansancloud.com/xianhua/2019_11/26/10/22/27_268.jpg?x-oss-process=style/preview_120'></image>
	     </view>
	  </view>
      <view class="agreement_block">
         <text class='agreementTip'>点击本机号码一键登录表示您已同意</text>
         <text class='agreementName' @click='tolinkUrl' data-url="custom_page_regist_agreement.html">《登录协议》</text>
      </view>
      
      <custom-page-index-component id="container" :receiveData="sendCustomPageData" v-if="sendCustomPageData" @refreshFun="getRefreshFun"></custom-page-index-component>
	</view>
</form>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      loginData:{},
	  loginState:false,
	  setting:null,
      backUrl:'',
      authorizationState:false,
      sendCustomPageData:null,
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    // wx.hideTabBar({})
    let that=this;
    console.log("======onLoad:wxLogin======", options);
    let sendCustomPageData = JSON.stringify({
      title: 'noTitle',
      url: "login"
    });
    that.setData({
      sendCustomPageData: sendCustomPageData
    });
    if(options.url){
        that.setData({backUrl:decodeURIComponent(options.url)})
    }
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.loginState=false;
    getApp().globalData.addAuthorizationListenerItem(that)
	that.setData({setting:getApp().globalData.setting})
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; // 下拉刷新的时候首先判断存不存在tab
    console.log("下拉");
    that.refreshPage();
    wx.stopPullDownRefresh();
  },
  methods: {
    bindGetUserInfo: function (e) {
      let that = this;
      that.setData({authorizationState:true})
      console.log(e.detail.userInfo)
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        console.log('用户按了允许授权按钮')
        if (getApp().globalData.loginUser && getApp().globalData.loginUser.platformUser&&!getApp().globalData.loginUser.platformUser.nickname) {
           getApp().globalData.sentWxUserInfo(getApp().globalData.loginUser)
        }
      } else {
        console.log('用户按了拒绝按钮')
        //用户按了拒绝按钮
      }
    },
    getStateData: function (state) {
      let that = this;
      console.log("===getStateData===", state);
      that.selectComponent("#container").setPopupState(state);
    },
    getPhoneNumber:function(e){
        let that=this;
        getApp().globalData.consoleFun('===getPhoneNumber===',[e]);
        getApp().globalData.getSessionFun(function(res){
            console.log("====getSessionFun====",res.data);
            if(res.data.errcode==0){
                let sessionData=res.data.relateObj.map
                let resutlData=e.detail;
                let params={
                    encryptedData:decodeURIComponent(resutlData.encryptedData),
                    iv:decodeURIComponent(resutlData.iv),
                    forceBind:1,
                    scene:getApp().globalData.more_scene||0,
                    miniOpenId:sessionData.openid,
                    sessionKey:sessionData.session_key,
                }
                that.loginState=true;
                getApp().globalData.toLogin('/decode_phone_with_auto_regist_or_login.html?jsonOnly=1',params,function(res){
                    console.log("====== res.data=========", res.data);
                    wx.hideLoading();
                    let resData=res.data
                    if (!resData.errcode || resData.errcode == '0') {
                      that.loginSuccessFun(resData,params)
                    } else {
                      that.loginState=false;
                      that.loginFailFun(resData)
                    }
                },function(res){
                    console.log(res);
                    wx.hideLoading();
                    that.loginState=false;
                    that.loginFailFun()
                })
            }else{
                getApp().globalData.showToastLoading('授权失败', true);
            }
        })
        
    },
    loginSuccessFun:function(resData,params){
        console.log("====loginSuccessFun===",resData);
        let that=this;
        let loginToken=resData.relateObj.platformUser.loginToken;
        that.$set(params,'loginToken',loginToken)
        getApp().globalData.setStorageFun("loginToken",loginToken)
        getApp().globalData.setStorageFun("loginParams",params)
        that.setData({
            loginData:resData.relateObj
        });
        if(that.backUrl){
            getApp().globalData.checkWxAuthUserInfo(function(){
                that.linkEvent(that.backUrl,'reLaunch');
            })
        }else{
            getApp().globalData.toIndex('reLaunch');
        }
    },
    getRefreshFun:function(){
        let that=this;
        that.linkEvent(that.backUrl,'reLaunch');
    },
    linkEvent:function(url,type){
        getApp().globalData.linkEvent(url,type)
    },
    loginFailFun:function(resData){
        console.log("====loginFailFun===",resData);
        let that=this
        wx.showToast({
          title: '登录失败，请重新登录',
          icon: 'none',
          duration: 2000
        });
        // let text=resData&&resData.errMsg?resData.errMsg:'登录失败，点击【确定】重新登录';
        // wx.showModal({
        //     title: '提示',
        //     content: text,
        //     success: function (res) {
        //       if (res.confirm) {
        //         // getApp().globalData.wxLogin('',function(data){
        //         //     console.log("====wxLogin11111====",data);
        //         //     // getApp().globalData.toIndex()
        //         //     that.loginState=false;
        //         //     getApp().globalData.showToastLoading('请重试登录', true);
        //         // },function(data){
        //         //     console.log("====wxLogin22222====",data);
        //         //     // getApp().globalData.toIndex('',"checkAuthorizationState")
        //         // })
        //       } else if (res.cancel) {
        //         // getApp().globalData.toIndex();
        //       }
        //     }
        // });
    },
	toAppLoginFun:function(){
		let that=this;
		let linkUrl="app_login_page.html"
		getApp().globalData.linkEvent(linkUrl);
	},
    setNavBar: function () {
      console.warn("1111111111111",getApp().globalData.setting);

      if (getApp().globalData.setting.platformSetting&&getApp().globalData.setting.platformSetting.siteTitle == '') {
        wx.setNavigationBarTitle({
          title: '首页'
        });
      } else {
        wx.setNavigationBarTitle({
          title: getApp().globalData.setting.platformSetting?getApp().globalData.setting.platformSetting.siteTitle:'默认首页'
        });
      }

      wx.setNavigationBarColor({
        frontColor: getApp().globalData.setting.platformSetting?getApp().globalData.setting.platformSetting.topColor.toLowerCase():'',
        backgroundColor: getApp().globalData.setting.platformSetting?getApp().globalData.setting.platformSetting.topBgColor:''
      });
    },
    // getStateData: function (state) {
    //   let that = this;
    //   console.log("===getStateData===", state, that.showAuthorizationPopup);
    //   let partialsName = JSON.parse(that.partialsName);
    //   partialsName.state = state;
    //   that.setData({
    //     partialsName: null
    //   });
    //   setTimeout(function () {
    //     that.setData({
    //       partialsName: JSON.stringify(partialsName)
    //     });
    //   }, 300);
    // },
    jumpToPage: function (shareParam) {
      if (shareParam.pageName == 'custom_page_index') {
        return;
      } else if (shareParam.pageName == 'shopping_car_list') {
        return;
      } else if (shareParam.pageName == 'custom_page_userinfo') {
        return;
      } else {
        let paramStr = getApp().globalData.jsonToStr(shareParam);
        wx.navigateTo({
          url: '/pages/' + shareParam.pageName + '/index' + paramStr
        });
      }
    },
    onPageScroll: function (object) {
		console.log('=====positionNotifyer==')
    },

    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget.dataset.url;
      getApp().globalData.linkEvent(linkUrl);
    },
    setPageName: function (urlStr) {
      let url = urlStr || "";
      let partialsName = "";

      if (url) {
        partialsName = JSON.stringify({
          url: url,
          state: this.showAuthorizationPopup
        });
      }

      this.setData({
        partialsName: partialsName
      });
      console.log("partialsName", this.partialsName);
    },
    refreshPage: function () {
      let that = this;
      console.log("首页刷新");
      that.setPageName();
      wx.showToast({
        title: '加载中...',
        icon: 'none',
        duration: 500
      });
      setTimeout(function () {
        that.setPageName('index');
        getApp().globalData.footerCount = 0;
      }, 500);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>